package com.fengzheng.basic.common.config.response;

import com.fengzheng.basic.common.config.response.exception.ServiceException;
import lombok.Data;
import java.io.Serializable;

/**
 * api通用返回数据
 * @author HU
 * @date 2022/1/19 14:28
 */
@Data
//api通用返回数据
public class ResultBean<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    //标识代码,1表示成功，非1表示出错
    private int code;

    //返回对象
    private T data;

    //异常信息
    private String msg;

    //没有data的成功和失败,成功是固定的，所以一般用于失败
    public void setCodeMsg(ResultCodeMsg codeMsg){
        this.msg = codeMsg.msg;
        this.code = codeMsg.code;
    }

    //没有data的固定的成功和失败
    public void setCodeMsg(boolean isSuccess){
        setCodeMsg(isSuccess?ResultCodeMsg.SUCCESS:ResultCodeMsg.FAIL);
    }

    public ResultBean() { }

    //没有data的成功和失败,成功是固定的，所以一般用于失败
    public ResultBean(ResultCodeMsg codeMsg) {
        setCodeMsg(codeMsg);
    }

    //没有data的固定的成功和失败
    public ResultBean(Boolean isSuccess) {
        setCodeMsg(isSuccess);
    }

    public ResultBean(T data) {
        this.data = data;
        setCodeMsg(ResultCodeMsg.SUCCESS);
    }

    public ResultBean(Throwable e) {
        this.msg = e.toString();
        setCodeMsg(ResultCodeMsg.FAIL);
        if(e instanceof ServiceException){
            this.msg = e.getMessage();
            this.code = ((ServiceException) e).getCode();
        }
    }

}
